package com.suker.jvm.hotspot.src.share.vm.classfile;

import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Array;

/**
 * 用于根据字符描述描述符获取方法的参数类型，返回类型等信息
 */
public class SignatureDescriptor {

    /**
     * (Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintStream;
     */
    private String signature;

    public SignatureDescriptor(String signature) {
        this.signature = signature.replace("/", ".");
    }


    /**
     * 根据描述符获取入参类型
     *
     * @return
     * @throws Exception
     */
    public Class<?>[] getParams() throws Exception {
        // 参数class描述符
        String paramClassStr = StrUtil.subBetween(signature, "(", ")");
        if (StrUtil.isEmpty(paramClassStr)) {
            return new Class<?>[0];
        }

        String[] array = paramClassStr.split(";");
        Class<?>[] classes = new Class[array.length];
        for (int i = 0; i < array.length; i++) {
            String classStr = array[i];
            if ("I".equals(classStr)) {
                classes[i] = int.class;
            } else if (classStr.startsWith("L")) {
                classes[i] = Class.forName(StrUtil.subAfter(classStr, "L", true));
            } else if (classStr.startsWith("[L")) {
                classes[i] = Array.newInstance(Class.forName(StrUtil.subAfter(classStr, "[L", true)), 0).getClass();
            }
        }
        return classes;
    }
}
